﻿using System;
using System.Configuration.Install;
using System.IO;
using System.Reflection;
using System.ServiceProcess;
using System.Threading;
using Grundy.Common;
using Grundy.Licensing.Server;

namespace Grund.Licensing.Server.Host
{
    class Host
    {
        private static IApplication _application;

        static void Main(string[] args)
        {
            if (System.Environment.UserInteractive)
            {

                if (args.ContainsIgnoreCase("-install_service"))
                {
                    ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                }
                else if (args.ContainsIgnoreCase("-uninstall_service"))
                {
                    ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                }
                else
                {
                    var worker = new Thread(() => { _application = Application.Instance; });
                    worker.Start();

                    Console.WriteLine("License server started, enter 'quit' to exit.");
                    ReadCommand();    
                }
            }
            else
            {
                ServiceBase.Run(new Service());
            }
        }

        private static void ReadCommand()
        {
            Console.Write("Command: ");
            var command = Console.ReadLine();
            if (command.EqualsIgnoreCase("Quit"))
            {
                _application.LicenseServer.Shutdown();
                Console.WriteLine("Shutting down...");
                Thread.Sleep(1000);
                Environment.Exit(0);
            }
            ReadCommand();
        }
    }
}
